﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using System.IO;

namespace Jobping.StickyBeak
{
	public class NLogRecorder : FileRecorder
	{
		public static readonly string LoggerName = "Jobping.StickyBeak";
		
		private readonly Logger logger = LogManager.GetLogger(LoggerName);

		public override void WriteRequest(string requestItem)
		{
			logger.Info(requestItem);
		}

		public override IEnumerable<string> GetPages()
		{
			var dir = new DirectoryInfo(this.GetLogDirectory());

			var files = dir.GetFiles("*.log", SearchOption.TopDirectoryOnly).OrderByDescending(x => x.LastWriteTimeUtc);

			foreach (var f in files)
			{
				yield return f.Name;
			}
		}

		public override IEnumerable<RequestLog> GetPage(string pageId)
		{
			var f = new FileInfo(Path.Combine(this.GetLogDirectory(), pageId));

			var logs = this.Parse(f).OrderByDescending(x => x.DateUtc);

			foreach (var log in logs)
			{
				yield return log;
			}
		}

		private string GetLogDirectory()
		{
			var rules = logger.Factory.Configuration.LoggingRules;

			foreach(var rule in rules)
			{
				if (rule.LoggerNamePattern != LoggerName)
					continue;

				string targetName = rule.Targets[0].Name;
				var target = logger.Factory.Configuration.FindTargetByName(targetName);

				string path = ((NLog.Targets.FileTarget)target).FileName;

				path = path.Replace("${basedir}", AppDomain.CurrentDomain.BaseDirectory);

				return System.IO.Path.GetDirectoryName(path);
			}

			throw new ApplicationException(LoggerName + " - Logger must be configured in the NLog.config file");	
		}		
	}
}
